package com.whmall.service.crm.util;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whmall.component.entity.dto.PageReqDTO;
import com.whmall.component.entity.dto.PageRspDTO;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * PageDTO工具类
 *
 * @author alex
 * @since 2020/7/21
 */
public abstract class PageDTOHelper {
    public static void startPage(PageReqDTO pageRequest) {
        Page<Object> page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        handleSort(page, pageRequest.getSortFields(), pageRequest.getSortOrders());
    }

    private static void handleSort(Page<Object> page, List<String> sortFields, List<String> sortOrders) {
        if (CollectionUtils.isEmpty(sortFields)) {
            return;
        }

        StringJoiner orderBy = new StringJoiner(", ");
        for (int i = 0; i < sortFields.size(); i++) {
            String sortField = sortFields.get(i);

            //
            // 如果ASC,DESC列表如果不是空的，说明指定了排序方向
            // 如果字段数大于排序方向的数量，超过的字段将不会指定方向，否则取对应位置的顺序
            if (!CollectionUtils.isEmpty(sortOrders)
                    && i < sortOrders.size()) {
                orderBy.add(sortField + " " + sortOrders.get(i));
            } else {
                orderBy.add(sortField);
            }
        }

        page.setOrderBy(orderBy.toString());
    }

    public static <T> PageRspDTO<T> toPageDTO(List<T> listAsPage) {
        return toPageDTO(new PageInfo<>(listAsPage));
    }

    public static <T> PageRspDTO<T> toPageDTO(PageInfo<T> pageInfo) {
        return PageRspDTO.<T>builder()
                .pageNum(pageInfo.getPageNum())
                .pageSize(pageInfo.getPageSize())
                .total((int) pageInfo.getTotal())
                .count(pageInfo.getPages())
                .records(pageInfo.getList())
                .build();
    }

    public static <T, R> PageRspDTO<R> toPageDTO(List<T> listAsPage, Function<T, R> mapper) {
        return toPageDTO(new PageInfo<>(listAsPage), mapper);
    }

    public static <T, R> PageRspDTO<R> toPageDTO(PageInfo<T> pageInfo, Function<T, R> mapper) {
        return PageRspDTO.<R>builder()
                .pageNum(pageInfo.getPageNum())
                .pageSize(pageInfo.getPageSize())
                .total((int) pageInfo.getTotal())
                .count(pageInfo.getPages())
                .records(pageInfo.getList()
                        .stream()
                        .map(mapper)
                        .collect(Collectors.toList()))
                .build();
    }


}
